<template>
  <div>
    <e-panel>
      <template #top>
        <e-search ref="queryRef" v-bind="queryProps" />
      </template>
      <e-table ref="tableRef" v-bind="tableProps" :actions="rowActions">
        <template #toolBarEnd>
          <n-button v-auth="['gen-table-ai']" secondary type="success" @click="genAiModalRef!.show()">
            <template #icon>
              <Icon icon-name="InfiniteOutline" />
            </template>
            AI建表
          </n-button>
        </template>
        <template ##enableFlag="row">
          <n-tag :type="row.enableFlag ? 'success' : 'warning'" :bordered="false">{{ row.enableFlag_dict }}</n-tag>
        </template>
      </e-table>
      <template #bottom>
        <e-form
          ref="formRef"
          v-bind="formProps"
          :cols="6"
          :before-submit="formatGenTableSubmitData"
          :format-form-data="formatGenTableRowData"
          w-size="100%"
          lazy-form
        >
          <gen-form-modal v-if="showTableFields" v-model:active-tab="activeTab" v-model:table-fields="tableFields" />
        </e-form>
      </template>
    </e-panel>
    <gen-modal ref="genModalRef" @ok="previewHandler" />
    <gen-ai-modal ref="genAiModalRef" @complete="aiGenCompleteHandler" />
    <gen-preview ref="genPreviewRef" />
  </div>
</template>

<script lang="ts" setup>
  import GenTable, { GenPreviewFile, GenTableField, GenTableIndex } from './model'
  import { uniqueId } from 'lodash-es'
  import { ButtonActions } from '@/components/ActionButton/commonActions'
  import { FormTypeEnum } from 'easy-descriptor'
  import GenAiModal from './comp/GenAiModal.vue'
  import GenPreview from './comp/GenPreview.vue'
  import GenModal from '@/views/gen/table/comp/GenModal.vue'
  import { usePanel } from '@/components/ext'
  import Model from '@/views/gen/table/model'
  import { FormatFormData } from '@/components/ext/types'
  import GenFormModal from '@/views/gen/table/comp/GenFormModal.vue'

  defineOptions({
    name: 'GenTableList'
  })

  const genAiModalRef = useCompRef(GenAiModal)
  const genPreviewRef = useCompRef(GenPreview)
  const genModalRef = useCompRef(GenModal)

  const activeTab = ref<string>('db')
  const showTableFields = ref<boolean>(false)

  onMounted(() => {
    setTimeout(() => {
      nextTick(() => {})
      showTableFields.value = true
    }, 1000)
  })

  /**
   * GenTable 初始化配置
   */
  const {
    refs: { tableRef, formRef, queryRef },
    commProps: { tableProps, formProps, queryProps }
  } = usePanel(Model)

  const tableFields = ref<GenTableField[]>([])
  const tableIndexs = ref<GenTableIndex[]>([])
  const tempIdPrefix = 'tmp_'

  /**
   * 提交前格式化生成表单数据
   * @param formData
   */
  const formatGenTableSubmitData: FormatFormData<Model> = async (formData) => {
    activeTab.value = 'db'
    formData.tableFields = tableFields.value.map(({ id, ...fields }) => ({ id: id?.startsWith(tempIdPrefix) ? undefined : id, ...fields }))
    formData.tableIndexs = tableIndexs.value.map(({ id, ...indexs }) => ({ id: id?.startsWith(tempIdPrefix) ? undefined : id, ...indexs }))
    return formData
  }

  /**
   * 数据回填时格式化生成表单数据
   * @param formData
   */
  const formatGenTableRowData: FormatFormData<Model> = async (formData) => {
    activeTab.value = 'db'
    formData.tableFields = tableFields.value = formData?.tableFields ?? []
    formData.tableIndexs = tableIndexs.value = formData?.tableIndexs ?? []
    // formData.tableFields = tableFields.value
    // formData.tableIndexs = tableIndexs.value
    return formData
  }

  /**
   * 处理AI生成完成的回调函数
   * @param data GenTable类型的数据，包含表单数据和表单字段
   * 此函数的目的是将AI生成的表单数据和字段添加到现有的表单中
   */
  const aiGenCompleteHandler = (data: GenTable) => {
    console.debug('aiGenCompleteHanlder: ', data)
    formRef.value?.open(FormTypeEnum.ADD)
    nextTick(() => {
      const { tableFields: _tableFields = [], ...genTable } = data
      tableFields.value = _tableFields
        .filter(({ columnName }) => !tableFields.value.some((item) => columnName === item.columnName))
        .map((item) => ({ id: uniqueId(tempIdPrefix), ...item }))
      // tableFields.value.push(
      //   ..._tableFields
      //     .filter(({ columnName }) => !tableFields.value.some((item) => columnName === item.columnName))
      //     .map((item) => ({ id: uniqueId(tempIdPrefix), ...item }))
      // )
      formRef.value?.setFormData(genTable)
    })
  }

  const previewHandler = (files: GenPreviewFile[], name: string) => {
    genPreviewRef.value!.open({
      files,
      name
    })
  }

  // 定义行操作的数组，用于表格中每行的按钮操作
  const rowActions: ButtonActions = [
    {
      action: 'auth',
      html: '代码生成',
      text: true,
      type: 'info',
      perms: 'gencode',
      handle: ({ row }) => genModalRef.value!.open(row)
    },
    'edit',
    'delete'
  ]
</script>

<style scoped lang="less">
  :deep(.n-data-table-td--center-align) {
    .n-form-item-blank {
      display: flex;
      justify-content: center;
    }
  }
</style>
